package com.chaos.meta.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONObject;
import com.chaos.meta.common.CommonResult;
import com.chaos.meta.common.CustomHandler;
import com.chaos.meta.common.MailService;
import com.chaos.meta.util.JedisCacheUtil;
import com.chaos.meta.util.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author naicha
 * @date 2021/8/7 10:32
 */
@RestController
@RequestMapping(value = "/test")
@Api("xxx操作")
public class CommonController {

    @Autowired
    private MailService sMail;

    @Autowired
    private JedisCacheUtil jedis;

    /**
     * @param email
     * @return CommonResult
     */
    @ApiOperation("发送验证码到邮箱")
    @PostMapping("/sendMessageByMail")
    public ResponseEntity<CommonResult> sendMessageByMail(@RequestBody String email)
    {
        CommonResult result = new CommonResult();
        result.setResultCode("0");
        result.setResultMessage("SUCCESS");
        try {
            String code = StringUtil.generateRandomString(6);
            sMail.sendSimpleMail("Verification Code:", code, new String[]{}, new String[]{}, email);
            jedis.set(email, code, 120);
        } catch (Exception e) {
            result.setResultCode("-1");
            result.setResultMessage("send email error, please contact the administrator!");
            return new ResponseEntity<>(result, HttpStatus.OK);
        }
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    /**
     * @param verificationInfo
     * @return CommonResult
     */
    @ApiOperation("验证验证码")
    @PostMapping("/validateCode")
    public ResponseEntity<CommonResult> validateCode(@RequestBody JSONObject verificationInfo)
    {
        CommonResult result = new CommonResult();
        try {
            String email = verificationInfo.getString("email");
            String code = verificationInfo.getString("code");
            String codeInRedis = jedis.get(email);
            if( !jedis.existKey(email) || codeInRedis == null || !codeInRedis.equals(code))
            {
                result.setResultCode("3");
                result.setResultMessage("verification code is incorrect or invalid, please sent again!");
            }else {
                jedis.delKey(email);
                result.setResultCode("0");
                result.setResultMessage("SUCCESS");
            }
            return new ResponseEntity<>(result, HttpStatus.OK);
        } catch (Exception e) {
            result.setResultCode("-1");
            result.setResultMessage("validate code failed, please contact the administrator!");
            return new ResponseEntity<>(result, HttpStatus.OK);
        }
    }

    @ApiOperation("get")
    @GetMapping(value = "/testGet")
    public ResponseEntity<CommonResult> testGet(HttpServletRequest request, HttpServletResponse response, @RequestParam(name = "userId", required = true) String userId) throws Exception
    {
        return new ResponseEntity<>(null, HttpStatus.OK);
    }

    @ApiOperation("post")
    @PostMapping(value = "/testPost")
    public void testPost(HttpServletRequest request, HttpServletResponse response, @RequestBody JSONObject requestBody, MultipartFile multipartFile) throws Exception
    {
    }

    @ApiOperation("download")
    @GetMapping(value = "/download")
    public ResponseEntity<Resource> download(HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        return new ResponseEntity<>(new FileSystemResource("F:\\license.txt"), HttpStatus.OK);
    }

    private static void responseFile(HttpServletRequest request, HttpServletResponse response, String fileName, Map<String, List<List<String>>> data) throws IOException {
        String sheetName = fileName;
        fileName = StringUtil.encodeFileName(fileName, request);
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".xlsx");
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        List<List<String>> header = new ArrayList<>();
        List<List<String>> content = new ArrayList<>();
        if (data.get("header") != null && data.get("content") != null)
        {
            header = data.get("header");
            content = data.get("content");
        }
        try {
            EasyExcel.write(response.getOutputStream()).head(header).registerWriteHandler(new CustomHandler())
                    .sheet(sheetName).doWrite(content);
        } finally {
            response.getOutputStream().close();
        }
    }
}
